package com.jourwon.spring.boot.service.impl;

import com.alibaba.fastjson.JSON;
import com.jourwon.spring.boot.core.DynamicJdbcTemplate;
import com.jourwon.spring.boot.enums.DataSourceNameEnum;
import com.jourwon.spring.boot.model.entity.User;
import com.jourwon.spring.boot.model.vo.UserVO;
import com.jourwon.spring.boot.service.UserService;
import com.jourwon.spring.boot.util.BeanTransformUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 用户表 服务实现类
 *
 * @author JourWon
 * @date 2021-02-10
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    private static final String SQL = "select * from user";

    @Resource
    private DynamicJdbcTemplate dynamicJdbcTemplate;

    @Override
    public List<UserVO> listMaster() {
        return listUserVO(DataSourceNameEnum.MASTER.getDataSourceName());
    }

    @Override
    public List<UserVO> listSlave() {
        return listUserVO(DataSourceNameEnum.SLAVE.getDataSourceName());
    }

    private List<UserVO> listUserVO(String dsName) {
        log.info("使用[{}]数据源查询用户信息", dsName);
        List<Map<String, Object>> master = dynamicJdbcTemplate.queryForList(dsName, SQL);
        List<User> users = getUsers(master);
        log.info("[{}]数据源返回用户列表:{}", dsName, JSON.toJSONString(users));
        return BeanTransformUtils.transformList(users, UserVO.class);
    }

    private List<User> getUsers(List<Map<String, Object>> master) {
        List<User> users = new ArrayList<>();
        for (Map<String, Object> map : master) {
            User user = JSON.parseObject(JSON.toJSONString(map), User.class);
            users.add(user);
        }
        return users;
    }

}
